using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace Test
{
  class SQL
  {
    string _cs;
    public SQL() : this("server=(local)\\sqlexpress;integrated security=sspi;") { }
    public SQL(params string[] args)
    {
      if(args.Length==2)
        _cs=string.Format("server={0};database={1};integrated security=sspi;",args);
      else
        throw new Exception();
    }
    public SQL(string cs) { _cs=cs; }


    public DataTable Query(string sql,params object[] args)
    {
      string qry=string.Format(sql,args);
      DataTable ret=new DataTable();
      using(SqlDataAdapter adp=new SqlDataAdapter(qry,_cs))
      {
        adp.SelectCommand.CommandTimeout=0;
        adp.Fill(ret);
      }
      return ret;
    }
    public DataSet QuerySet(string sql,params object[] args)
    {
      string qry=string.Format(sql,args);
      DataSet ret=new DataSet();
      using(SqlDataAdapter adp=new SqlDataAdapter(qry,_cs))
      {
        adp.SelectCommand.CommandTimeout=180;
        adp.Fill(ret);
      }
      return ret;
    }
    public int NonQry(string sql,params object[] args)
    {
      string qry=string.Format(sql,args);
      int ret=-1;
      using(SqlConnection con=new SqlConnection(_cs))
      using(SqlCommand cmd=new SqlCommand(qry,con))
      {
        con.Open();
        ret=cmd.ExecuteNonQuery();
        con.Close();
      }
      return ret;
    }

    public object Scalar(string sql,params object[] args)
    {
      //System.Diagnostics.Stopwatch sw=System.Diagnostics.Stopwatch.StartNew();
      
      string qry=string.Format(sql,args);
      object ret=null;
      using(SqlConnection con=new SqlConnection(_cs))
      using(SqlCommand cmd=new SqlCommand(qry,con))
      {
        con.Open();
        ret=cmd.ExecuteScalar();
        con.Close();
      }
      //Console.WriteLine("------"+sw.Elapsed);
      return ret;
    }
  }
}
